<template>
  <div :class="['home-container', isTechTheme ? 'tech-theme' : '']" :style="customBgUrl ? {background: `url('${customBgUrl}') center/cover no-repeat`} : {}">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="floating-shape shape-1"></div>
      <div class="floating-shape shape-2"></div>
      <div class="floating-shape shape-3"></div>
    </div>

    <div class="content-wrapper">
      <!-- 顶部区域：时间和搜索栏 -->
      <div class="top-section">
        <div class="time-display">{{ currentTime }}</div>
        <div class="search-area">
          <SearchBar />
        </div>
      </div>

      <!-- 底部工具栏 -->
      <div class="bottom-toolbar">
        <div class="tools-grid">
          <div
            v-for="tool in tools"
            :key="tool.id"
            class="tool-item"
            @click="navigateTo(tool.path)"
            :data-tooltip="tool.name"
          >
            <div class="tool-icon">
              <i :class="tool.icon"></i>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import SearchBar from "../components/SearchBar.vue";

// 新增：全局书签和历史
const isExtension = typeof chrome !== 'undefined' && chrome.bookmarks && chrome.history;
const extensionBookmarks = ref([]);
const extensionHistory = ref([]);
let bookmarkListener = null;
let historyInterval = null;

// 时间相关
const currentTime = ref('');
let timeInterval = null;

const updateTime = () => {
  const now = new Date();
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  currentTime.value = `${hours}:${minutes}`;
};

const syncBookmarks = () => {
  chrome.bookmarks.getTree((tree) => {
    window.extensionBookmarks = tree;
  });
};
const syncHistory = () => {
  chrome.history.search({ text: '', maxResults: 50 }, (results) => {
    window.extensionHistory = results;
  });
};

const router = useRouter();

const tools = computed(() => [
  {
    id: 1,
    name: "WebP 转换器",
    description: "批量将图片转换为WebP格式，支持拖拽上传和批量处理",
    icon: "fas fa-images",
    path: "/webp-converter",
  },
  {
    id: 2,
    name: "文本比对",
    description: "智能比较两段文本的差异，高亮显示变化内容",
    icon: "fas fa-file-alt",
    path: "/text-diff",
  },
  {
    id: 3,
    name: "JSON美化",
    description: "格式化JSON数据，支持树状展示、折叠和复制功能",
    icon: "fas fa-code",
    path: "/json-prettify",
  },
  {
    id: 4,
    name: "错误监控",
    description: "实时监控和查看应用错误，支持错误上报和统计分析",
    icon: "fas fa-bug",
    path: "/error-monitor",
  },
  {
    id: 5,
    name: "时间戳转换",
    description: "在时间戳和日期格式之间进行快速转换",
    icon: "fas fa-clock",
    path: "/timestamp",
  },
  {
    id: 6,
    name: "Base64 编解码",
    description: "文本和Base64编码之间的相互转换，支持图片预览",
    icon: "fas fa-file-code",
    path: "/base64",
  },
  {
    id: 7,
    name: "API 请求测试",
    description: "轻量级的HTTP请求客户端，支持多种请求方式",
    icon: "fas fa-paper-plane",
    path: "/api-tester",
  },
  {
    id: 8,
    name: "暂存室",
    description: "安全暂存文本和文件，支持多端同步和数据导出",
    icon: "fas fa-archive",
    path: "/storage",
  },
  {
    id: 9,
    name: "备忘录",
    description: "支持房间概念的备忘录工具，任务清单模式，富文本和Markdown语法",
    icon: "fas fa-sticky-note",
    path: "/memo",
  },
]);

const navigateTo = (path) => {
  router.push(path);
};

// 主题状态
const currentTheme = ref("default-theme");

// 主题判断
const isTechTheme = computed(() => {
  return currentTheme.value === "tech-theme";
});

// 监听主题变化
function updateTheme() {
  const theme = localStorage.getItem("theme") || "default-theme";
  currentTheme.value = theme;
}

// 监听 localStorage 变化
function handleStorageChange(e) {
  if (e.key === "theme") {
    updateTheme();
  }
}

const customBgUrl = ref('');

onMounted(() => {
  updateTheme();
  updateTime();
  timeInterval = setInterval(updateTime, 1000);
  
  window.addEventListener("storage", handleStorageChange);
  window.addEventListener("themeChanged", updateTheme);

  // 新增：扩展环境下同步书签和历史
  if (isExtension) {
    syncBookmarks();
    syncHistory();
    // 实时监听书签变化
    bookmarkListener = () => syncBookmarks();
    chrome.bookmarks.onChanged.addListener(bookmarkListener);
    chrome.bookmarks.onCreated.addListener(bookmarkListener);
    chrome.bookmarks.onRemoved.addListener(bookmarkListener);
    chrome.bookmarks.onMoved.addListener(bookmarkListener);
    chrome.bookmarks.onChildrenReordered.addListener(bookmarkListener);
    chrome.bookmarks.onImportEnded.addListener(bookmarkListener);
    // 定时刷新历史（每60秒）
    historyInterval = setInterval(syncHistory, 60000);
  }

  const localBg = localStorage.getItem('customBgUrl');
  if (localBg) customBgUrl.value = localBg;
});

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval);
  }
  window.removeEventListener("storage", handleStorageChange);
  window.removeEventListener("themeChanged", updateTheme);
  // 清理监听和定时器
  if (isExtension) {
    if (bookmarkListener) {
      chrome.bookmarks.onChanged.removeListener(bookmarkListener);
      chrome.bookmarks.onCreated.removeListener(bookmarkListener);
      chrome.bookmarks.onRemoved.removeListener(bookmarkListener);
      chrome.bookmarks.onMoved.removeListener(bookmarkListener);
      chrome.bookmarks.onChildrenReordered.removeListener(bookmarkListener);
      chrome.bookmarks.onImportEnded.removeListener(bookmarkListener);
    }
    if (historyInterval) {
      clearInterval(historyInterval);
    }
  }
});
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  position: relative;
  overflow: hidden;
}

.home-container.tech-theme {
  background: #0a1833;
  background-image: radial-gradient(
      circle at 20% 80%,
      #1e90ff 0%,
      transparent 50%
    ),
    radial-gradient(circle at 80% 20%, #00e0ff 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, #7f7fff 0%, transparent 50%);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.home-container.tech-theme .floating-shape {
  background: linear-gradient(135deg, #1e90ff, #00e0ff);
  opacity: 0.18;
  animation: techFloat 8s ease-in-out infinite;
}

.shape-1 {
  width: 100px;
  height: 100px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 15%;
  animation-delay: 2s;
}

.shape-3 {
  width: 80px;
  height: 80px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

@keyframes techFloat {
  0%,
  100% {
    transform: translateY(0) rotate(0deg);
    opacity: 0.18;
  }
  50% {
    transform: translateY(-30px) rotate(180deg);
    opacity: 0.35;
  }
}

.content-wrapper {
  position: relative;
  z-index: 2;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 2rem 1rem 1rem;
}

/* 顶部区域：时间和搜索栏 */
.top-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2rem;
  margin-top: 2rem;
  margin-bottom: auto;
}

.time-display {
  font-size: 4rem;
  font-weight: 300;
  color: white;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  letter-spacing: 0.1em;
  text-align: center;
}

.search-area {
  width: 100%;
  max-width: 700px;
  display: flex;
  justify-content: center;
}

/* 底部工具栏 */
.bottom-toolbar {
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(25px);
  -webkit-backdrop-filter: blur(25px);
  border-radius: 24px;
  padding: 0.8rem;
  margin: 0.5rem auto;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12), 
              0 2px 8px rgba(0, 0, 0, 0.08),
              inset 0 1px 0 rgba(255, 255, 255, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.25);
  width: fit-content;
  max-width: 90vw;
}

.tools-grid {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 0.25rem;
  flex-wrap: wrap;
}

.tool-item {
  position: relative;
  width: 42px;
  height: 42px;
  background: rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08), 
              inset 0 1px 0 rgba(255, 255, 255, 0.6);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.tool-item:hover {
  transform: translateY(-3px) scale(1.05);
  background: rgba(102, 126, 234, 0.8);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3), 
              0 4px 12px rgba(0, 0, 0, 0.1),
              inset 0 1px 0 rgba(255, 255, 255, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.4);
}

.tool-item:hover .tool-icon {
  color: white;
}

.tool-icon {
  font-size: 18px;
  color: #667eea;
  transition: all 0.3s ease;
}

/* Tooltip 样式 */
.tool-item::before {
  content: attr(data-tooltip);
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 6px 10px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  pointer-events: none;
  z-index: 1000;
  margin-bottom: 8px;
}

.tool-item::after {
  content: '';
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 4px solid rgba(0, 0, 0, 0.8);
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  pointer-events: none;
  z-index: 1000;
  margin-bottom: 4px;
}

.tool-item:hover::before,
.tool-item:hover::after {
  opacity: 1;
  visibility: visible;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .content-wrapper {
    padding: 1rem 0.5rem;
  }
  
  .top-section {
    gap: 1.5rem;
    margin-top: 1rem;
  }
  
  .time-display {
    font-size: 3rem;
  }
  
  .search-area {
    max-width: 90%;
  }
  
  .tools-grid {
    gap: 0.2rem;
  }
  
  .tool-item {
    width: 38px;
    height: 38px;
  }
  
  .tool-icon {
    font-size: 16px;
  }
  
  .bottom-toolbar {
    margin: 0.3rem auto;
    padding: 0.6rem;
  }
  
  /* 移动端tooltip调整 */
  .tool-item::before {
    font-size: 11px;
    padding: 5px 8px;
    margin-bottom: 6px;
  }
  
  .tool-item::after {
    margin-bottom: 2px;
  }
}

@media (max-width: 480px) {
  .top-section {
    gap: 1rem;
    margin-top: 0.5rem;
  }
  
  .time-display {
    font-size: 2.5rem;
  }
  
  .search-area {
    max-width: 95%;
  }
  
  .tool-item {
    width: 36px;
    height: 36px;
  }
  
  .tool-icon {
    font-size: 14px;
  }
  
  .bottom-toolbar {
    padding: 0.5rem;
  }
}
</style>
